package com.ukee.birthday.common.utils;


import com.ukee.birthday.common.manager.TrustAnyHostnameVerifier;
import com.ukee.birthday.common.manager.TrustAnyTrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    public static String doGet(String url, Map<String, String> param, Map<String, String> header) {

        // 创建Httpclient对象
//        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpClient httpclient = null;
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            httpclient = new SSLClient();
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            if (header != null) {
                for (String key : header.keySet()) {
                    httpGet.addHeader(key, header.get(key));
                }
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doGet(String url, Map<String, String> param) {
        return doGet(url, param, null);
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> header) {
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String key : header.keySet()) {
                    httpPost.addHeader(key, header.get(key));
                }
            }
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPostObject(String url, Map<String, String> param, Map<String, String> header) {
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String key : header.keySet()) {
                    httpPost.addHeader(key, header.get(key));
                }
            }
            // 创建参数列表
//            if (param != null) {
//                List<NameValuePair> paramList = new ArrayList<>();
//                for (String key : param.keySet()) {
//                    paramList.add(new BasicNameValuePair(key, param.get(key).toString()));
//                }
//                // 模拟表单
//                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
//
//                httpPost.setEntity(entity);
//            }
            MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
            reqEntity
                    //设置编码，这两个一定要加，不然文件的文件名是中文就会乱码
                    .setCharset(Charset.forName("utf-8"))
                    //默认是STRICT模式，用这个就不能使用自定义的编码了
                    .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)//也可以使用reqEntity.setLaxMode();具体的可以查看MultipartEntityBuilder类
                    //这个方法其实就是addPart(name, new StringBody(text, contentType));
                  ;

            if (null != param.get("id") && !param.get("id").equals("")){
                reqEntity.addPart("id", new StringBody(param.get("id")));
            }
            if (null != param.get("touristName") && !param.get("touristName").equals("")){
                reqEntity.addPart("touristName", new StringBody(param.get("touristName")));
            }
            if (null != param.get("touristName") && !param.get("touristName").equals("")){
                reqEntity.addPart("touristName", new StringBody(param.get("touristName")));
            }
            if (null != param.get("idCard") && !param.get("idCard").equals("")){
                reqEntity.addPart("idCard", new StringBody(param.get("idCard")));
            }
            if (null != param.get("tel") && !param.get("tel").equals("")){
                reqEntity.addPart("tel", new StringBody(param.get("tel")));
            }
            if (null != param.get("feature") && !param.get("feature").equals("")){
                reqEntity.addPart("feature", new StringBody(param.get("feature")));
            }
            if (null != param.get("file") && !param.get("file").equals("")){
                File file = new File(param.get("file"));
                reqEntity.addPart("file", new FileBody(file));
            }

            httpPost.setEntity(reqEntity.build());
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url, Map<String, String> param) { return doPost(url, param, null); }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, Map<String, String> header, String json) {
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            if (header != null) {
                for (String key : header.keySet()) {
                    httpPost.addHeader(key, header.get(key));
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPostXml(String url, String entityStr) {
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(entityStr, ContentType.APPLICATION_FORM_URLENCODED);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPostFormData(String url, String entityStr, Map<String, String> header) {
        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            httpClient = new SSLClient();
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求头
            if (header != null) {
                for (String key : header.keySet()) {
                    httpPost.addHeader(key, header.get(key));
                }
            }
            // 创建请求内容
            StringEntity entity = new StringEntity(entityStr, ContentType.MULTIPART_FORM_DATA);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String httpsRequest(String url, String filePath, Map<String, String> map) throws NoSuchAlgorithmException, KeyManagementException {
        String resultString = null;
        SSLContext sslContext = SSLContext.getInstance("SSL");
        X509TrustManager tm = new TrustAnyTrustManager();
        sslContext.init(null, new TrustManager[]{ tm },
                new java.security.SecureRandom());
        HttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(new TrustAnyHostnameVerifier())
                .setSSLContext(sslContext).build();

        try {
            HttpPost httpPost = new HttpPost(url);
            FileBody bin = new FileBody(new File(filePath));
            if (map != null) {
                for (String key : map.keySet()) {
                    httpPost.setHeader(key, map.get(key));
                }
            }
            MultipartEntity reqEntity = new MultipartEntity();
            // image为请求后台的文件属性名
            reqEntity.addPart("image", bin);
            httpPost.setEntity(reqEntity);

            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity resEntity = response.getEntity();
                resultString = EntityUtils.toString(resEntity, "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.getConnectionManager().shutdown();
            } catch (Exception ignore) {

            }
        }

        return resultString;
    }
}
